#!/bin/bash

. $ZMICRO_HOME/commands/machine/lvm/config

is_lvm_created() {
  sudo vgs | grep $VG_NAME >> /dev/null 2>&1
  if [ "$?" != "0" ]; then
    echo "false"
    return
  fi

  echo "true"
}

is_device() {
  local device=$1
  echo $device | grep "^/dev/" >> /dev/null 2>&1
  if [ "$?" = "0" ]; then
    echo "true"
    return
  fi

  echo "false"
}

is_mounted() {
  if [ "$MOUNT_PATH" = "" ]; then
    log::error "error: config MOUNT_PATH not load"
    exit 1
  fi

  sudo mount | grep $MOUNT_PATH >> /dev/null 2>&1
  if [ "$?" = "0" ]; then
    echo "true"
  else
    echo "false"
  fi
}

remove() {
  if [ "$(is_mounted)" = "true" ]; then
    log::error "error: lvm is being mounted, you cannot remove device in mounted status"
    log::error "  Data is important, so your should stop processes in $MOUNT_PATH,"
    log::error "   then unmount device: /dev/$VG_NAME/$LV_NAME"
    log::error "  "
    log::error "  How to unmount:"
    log::error "    $ sudo unmount /dev/$VG_NAME/$LV_NAME"
    log::error " "
    log::error "  Then try to remove device again"
    exit 1
  fi

  local device=$1
  # /dev/sda => sda
  local deviceName=$(echo $device | sed -e "s%/dev/%%g")

  if [ "$VG_NAME" = "" ] || [ "$LV_NAME" = "" ] || [ "$MOUNT_PATH" = "" ]; then
    log::error "lvm config not load"
    exit 1
  fi

  if [ "$(is_device $device)" = "false" ]; then
    log::error "device should start with /dev/*, but found: ${device}"
    exit 1
  fi

  # 1.initial physical volume
  sudo pvs | grep $device >> /dev/null 2>&1
  if [ "$?" != "0" ]; then
    log::success "lvm device(${device}) not found, maybe removed before"
    exit 0
  fi

  # 1.remove from volumn group(vg)
  sudo vgreduce $VG_NAME $device
  if [ "$?" != "0" ]; then
    log::error "error: failed to remove lvm physical device from volume group"
    exit 1
  fi

  # 2.remove from physical volume(pv)
  sudo pvremove $device
  if [ "$?" != "0" ]; then
    log::error "error: failed to remove lvm physical device from physical volume"
    exit 1
  fi

  log::success "remove lvm device success: ${device}"
}

help() {
  echo "Usage:"
  echo "  zmachine lvm remove <device>"
  echo ""
  echo "Example:"
  echo "  remove /dev/sda:"
  echo "    zmachine lvm remove /dev/sda"
  echo ""
}

core() {
  if [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
    help
    exit 0
  fi

  local device=$1
  if [ "$device" = "" ]; then
    log::error "device is required"
    exit 1
  fi

  remove $device
}

run() {
  core $@
}

run $@
